﻿using Microsoft.EntityFrameworkCore;
using Super.Admin.Entities;

namespace Super.Admin.EFCore
{
    public class SuperDataBaseDbContext : DbContext
    {
        public SuperDataBaseDbContext(DbContextOptions<SuperDataBaseDbContext> options) : base(options) { }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<UserEntity>().HasIndex(u => u.UserName).IsUnique();
            modelBuilder.Entity<PermissionEntity>().Property(e => e.Icon).HasColumnType("BLOB");
            modelBuilder.Entity<IconEntity>().Property(e => e.Value).HasColumnType("BLOB");
            // 联合主键
            modelBuilder.Entity<RolePermissionEntity>().HasKey(e => new { e.RoleId, e.PermissionId });
            modelBuilder.Entity<UserRoleEntity>().HasKey(e => new { e.UserId, e.RoleId });
            modelBuilder.Entity<UserCommonPermissionEntity>().HasKey(e => new { e.UserId, e.PermissionId });
            // 一个用户有很多角色 用外键关联
            modelBuilder.Entity<UserEntity>().HasMany(u => u.UserRoles).WithOne(u => u.User).HasForeignKey(u => u.UserId);
            modelBuilder.Entity<RoleEntity>().HasMany(r => r.UserRoles).WithOne(r => r.Role).HasForeignKey(r => r.RoleId);
            // 用户部门表关联
            modelBuilder.Entity<UserEntity>().HasOne(u => u.Department).WithMany(d => d.Users).HasForeignKey(u => u.DepartmentId).IsRequired(false).OnDelete(DeleteBehavior.SetNull); // 部门删除时用户部门置空
            modelBuilder.Entity<DepartmentEntity>().HasOne(d => d.PersonInChargeModel).WithMany(u => u.ManangerDepartments).HasForeignKey(d => d.PersonInChargeId).OnDelete(DeleteBehavior.SetNull).IsRequired(false);
        }

        public DbSet<UserEntity> Users { get; set; }  // 用户表
        public DbSet<PermissionEntity> Permissions { get; set; }  // 权限表
        public DbSet<IconEntity> Icons { get; set; }  // 图标表
        public DbSet<RoleEntity> Roles { get; set; }  // 角色表
        public DbSet<RolePermissionEntity> RolePermissionEntities { get; set; } // 角色权限表
        public DbSet<DepartmentEntity> DepartmentEntities { get; set; } // 部门表
        public DbSet<UserRoleEntity> UserRoleEntities { get; set; } // 用户角色表
        public DbSet<AnnouncementEntity> AnnouncementEntities { get; set; } // 公告表
        public DbSet<UserOperateLogEntity> UserOperateLogEntities { get; set; } // 用户操作表
        public DbSet<UserCommonPermissionEntity> UserCommonPermissionEntities { get; set; } // 用户常用设置
    }
}
